<?php

namespace App\V3\V3_2_6\Services;

use App\Services\CommonService;
use App\V3\V3_2_6\Models\LogOutPackageModel;
use App\V3\V3_2_6\Models\LogOutStorageModel;
use App\V3\V3_2_6\Models\LogPackageContentModel;
use App\V3\V3_2_6\Models\LogPackageModel;
use App\V3\V3_2_6\Models\PackageContentModel;
use App\V3\V3_2_6\Models\PackageModel;
use App\V3\V3_2_6\Models\StorageManageModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class PackageService
{
    //条件搜索列表
    static public function withSearch($keyword, $data)
    {
        //获取套餐信息
        $packageInfo = PackageModel::getPackageInfo($keyword, $data);
        //获取套餐内容信息
        $packageContentInfo = PackageContentModel::getPackageContentInfo($keyword, $data);

        $packageId = [];
        foreach ($packageInfo as $v) {
            $packageId[] = $v['id'];
        }

        $packageContentParentId = [];
        foreach ($packageContentInfo as $v1) {
            $packageContentParentId[] = $v1['package_id'];
        }

        $arr = array_merge($packageContentParentId, $packageId);
        return PackageModel::withSearch($data, $arr);
    }

    //无条件搜索列表
    static public function withoutSearch($data)
    {
        return PackageModel::withoutSearch($data);
    }

    //新建套餐
    static public function add($data, $mainId)
    {
        //检查套餐是否存在
        if(!empty(PackageModel::checkInfo($data, $mainId))) {
            return 0;
        }

        return PackageModel::insertGetId([
            'package_name' => $data['package_name'],
            'main_id' => $mainId,
            'created_at' => time()
        ]);
    }

    //添加套餐内容
    static public function packageContentAdd($mainId, $data)
    {
        $storageManageInfo = StorageManageModel::packageContentGetStorageInfo($data);

        if($storageManageInfo['delete_flag'] == 1) {
            return -1;
        }

        $arr['materiel_first_class_id'] = $storageManageInfo['f_id'];
        $arr['materiel_first_class_name'] = $storageManageInfo['class_name'];
        $arr['materiel_first_class_no'] = $storageManageInfo['class_no'];
        $arr['package_id'] = $data['id'];
        $arr['materiel_class_id'] = $storageManageInfo['s_id'];
        $arr['materiel_class_name'] = $storageManageInfo['s_class_name'];
        $arr['materiel_class_no'] = $storageManageInfo['s_class_no'];
        $arr['storage_manage_id'] = $storageManageInfo['id'];
        $arr['type_id'] = $storageManageInfo['type_id'];
        $arr['materiel_name'] = $storageManageInfo['materiel_name'];
        $arr['type_name'] = $storageManageInfo['type_name'];
        $arr['materiel_no'] = $storageManageInfo['materiel_no'];
        $arr['storage_id'] = $storageManageInfo['storage_id'];
        $arr['storage_name'] = $storageManageInfo['storage_name'];
        $arr['storage_address'] = $storageManageInfo['storage_address'];
        $arr['num'] = $data['num'];
        $arr['main_id'] = $mainId;
        $arr['created_at'] = time();

        $checkPackageContent = PackageContentModel::checkPackageContent($data['id'], $storageManageInfo);

        if(!empty($checkPackageContent)) {
            return 0;
        }

        return PackageContentModel::insertGetId($arr);
    }

    static public function contentList($data)
    {
        return PackageContentModel::getContentInfo($data);
    }

    //修改套餐
    static public function edit($data, $mainId)
    {
        $condition[] = ['id', '!=', $data['id']];
        $condition['package_name'] = $data['package_name'];
        $condition['main_id'] = $mainId;

        $check = self::checkPackageInfo($condition);
        if(!empty($check)) {
            return 2;
        }

        $isUpdate = PackageModel::where('id', $data['id'])->lockForUpdate()->update(['package_name' => $data['package_name']]);

        if($isUpdate !== false) {
            return 1;
        }
        else {
            return 0;
        }
    }

    //修改套餐内容
    static public function packageContentEdit($data, $parentId)
    {
        $checkPackageContent = PackageContentModel::where([
            'storage_manage_id' => $data['storage_manage_id'],
            'package_id' => $data['package_id'],
        ])
            ->where('id', '!=', $data['id'])
            ->where('delete_flag', 0)
            ->first();

        if(!empty($checkPackageContent)) {
            return false;
        }

        PackageContentModel::where('id', $data['id'])->update($data);
        return true;
    }

    static private function checkPackageInfo($condition)
    {
        //检查套餐是否存在
        return PackageModel::where('delete_flag', 0)
            ->where($condition)
            ->first();
    }

    static public function packageStorageList($mainId, $data)
    {
        $packageContentInfo = PackageContentModel::where('id', $data['id'])->first();

        return StorageManageModel::packageStorageList($mainId, $packageContentInfo);
    }

    //添加套餐内容-可用库存物料信息
    static public function packageContentSelect($mainId, $data)
    {
        $packageContentInfo = PackageContentModel::where('package_id', $data['id'])
            ->where('delete_flag', 0)
            ->get()->toArray();

        $keyword = empty($data['keyword'])?'':$data['keyword'];
        $condition = [];
        if(!empty($data['materiel_class_id'])) {
            $condition['a.materiel_class_id'] = $data['materiel_class_id'];
        }

        $storageManageId = [];
        foreach($packageContentInfo as $key => $value) {
            $storageManageId[] = $value['storage_manage_id'];
        }

        $data['is_product_materiel'] = empty($data['is_product_materiel'])?0:1;

        $storageManageInfo = StorageManageModel::listForPackage($mainId, $keyword, $condition, $data);

        foreach($storageManageInfo as $k => $v) {
            if(in_array($v['id'], $storageManageId)) {
                $storageManageInfo[$k]['content_exist'] = 1;
            }
            else {
                $storageManageInfo[$k]['content_exist'] = 0;
            }
        }

        return $storageManageInfo;
    }

    //套餐出库
     static public function packageOut($data)
     {
         $packageInfo = PackageModel::select(
             'id',
             'package_name'
         )
             ->where([
                 'id' => $data['id'],
                 'main_id' => $data['main_id'],
                 'delete_flag' => 0
             ])
             ->with('hasManyContent', function($query) {
                 $query->where('delete_flag', 0);
             })
             ->first()->toArray();

         if(empty($packageInfo)) {
             return ['code' => 1, 'msg' => '套餐不存在，请重试', 'data' => ''];
         }

         $storageManageId = [];//套餐内容中库存信息id
         $packageContentStorageInfo = [];//套餐内容中库存内容id及套餐内物料组成数量
         foreach($packageInfo['has_many_content'] as $key => $value) {
             $storageManageId[] = $value['storage_manage_id'];
             $packageContentStorageInfo[$key] = [
                 'id' => $value['storage_manage_id'],
                 'num' => $value['num'] * $data['num'],//实际所需数量
             ];
         }

         //获取套餐内容绑定的库存信息
         $storageManageInfo = StorageManageModel::packageGetInfo($storageManageId);

         foreach($storageManageInfo as $kk => $val) {
             if($val['delete_flag'] == 1) {
                 return [
                     'code' => 1,
                     'msg' => '套餐内物料商品:`'.$val['materiel_name'].'-'.$val['type_name'].'不存在',
                     'data' => ''
                 ];
             }

             foreach($packageContentStorageInfo as $v) {
                 if($val['id'] == $v['id']) {
                     if($val['in_storage_num'] < sprintf('%.6f',$v['num'])) {
                         return [
                             'code' => 1,
                             'msg' => '套餐内物料商品:`'.$val['materiel_name'].'-'.$val['type_name'].'`库存数不足，当前库存:'.$val['in_storage_num'].',需出库数量:'.$v['num'],
                             'data' => ''
                         ];
                     }

                     if($val['virtual_storage_num'] < sprintf('%.6f',$v['num'])) {
                         return [
                             'code' => 1,
                             'msg' => '套餐内物料商品:`'.$val['materiel_name'].'-'.$val['type_name'].'`虚拟库存数不足',
                             'data' => ''
                         ];
                     }
                 }
             }
         }

         DB::beginTransaction();

         try {
             $packageLog = [
                 'package_id' => $packageInfo['id'],
                 'package_name' => $packageInfo['package_name'],
                 'num' => $data['num'],
                 'user_id' => $data['user_id'],
                 'main_id' => $data['main_id'],
                 'remark' => empty($data['remark'])?'':$data['remark'],
                 'created_at' => $data['time']
             ];
             $id = LogPackageModel::insertGetId($packageLog);

             $packageContentLog = [];
             $LogOutPackageData = [];
             $materielInfo = [];
             $logOutStorageData = [];
             foreach($storageManageInfo as $k1 => $v1) {
                 foreach($packageContentStorageInfo as $v2) {
                     if($v1['id'] == $v2['id']) {
                         $logOutStorageData[] = [
                             'type' => 6,
                             'storage_id' => $v1['storage_id'],
                             'storage_name' => $v1['storage_name'],
                             'storage_address' => $v1['storage_address'],
                             'next_storage_id' => 0,
                             'next_storage_name' => '',
                             'next_storage_address' => '',
                             'curr_storage_manage_id' => $v1['id'],
                             'next_storage_manage_id' => 0,
                             'materiel_class_id' => $v1['materiel_class_id'],
                             'materiel_class_name' => $v1['materiel_class_name'],
                             'materiel_class_no' => $v1['materiel_class_no'],
                             'is_package' => 1,//以此标记进行区分老版本套餐
                             'package_id' => $packageInfo['id'],
                             'materiel_type_id' => $v1['type_id'],
                             'materiel_name' => $v1['materiel_name'],
                             'type_name' => $v1['type_name'],
                             'materiel_no' => $v1['materiel_no'],
                             'operate_num' => $v2['num'],
                             'last_storage_num' => $v1['in_storage_num'],
                             'next_storage_num' => $v1['in_storage_num'] - ($v2['num']),
                             'sell_price' => $v1['selling_price'],
                             'profit_or_loss_ratio' => 0,
                             'materiel_mean_cost' => $v1['cost'],
                             'all_id_type' => 0,
                             'all_id' => 0,
                             'serial_number' => '',
                             'user_id' => $data['user_id'],
                             'main_id' => $data['main_id'],
                             'out_storage_time' => $data['time'],
                             'fact_out_time' => $data['time'],
                             'created_at' => $data['time'],
                             'shelf_id' => 0,
                             'location_id' => 0,
                             'remark' => empty($data['remark'])?'':$data['remark']
                         ];

//                         $packageContentLog[$k1]['log_package_id'] = $id;
//                         $packageContentLog[$k1]['package_id'] = $packageInfo['id'];
//                         $packageContentLog[$k1]['storage_id'] = $v1['storage_id'];
//                         $packageContentLog[$k1]['storage_name'] = $v1['storage_name'];
//                         $packageContentLog[$k1]['storage_address'] = $v1['storage_address'];
//                         $packageContentLog[$k1]['materiel_class_id'] = $v1['materiel_class_id'];
//                         $packageContentLog[$k1]['materiel_class_name'] = $v1['materiel_class_name'];
//                         $packageContentLog[$k1]['materiel_class_no'] = $v1['materiel_class_no'];
//                         $packageContentLog[$k1]['materiel_type_id'] = $v1['type_id'];
//                         $packageContentLog[$k1]['out_storage_manage_id'] = $v1['id'];
//                         $packageContentLog[$k1]['materiel_name'] = $v1['materiel_name'];
//                         $packageContentLog[$k1]['type_name'] = $v1['type_name'];
//                         $packageContentLog[$k1]['materiel_no'] = $v1['materiel_no'];
//                         $packageContentLog[$k1]['operate_num'] = $v2['num'] * $data['num'];
//                         $packageContentLog[$k1]['last_storage_num'] = $v1['in_storage_num'];
//                         $packageContentLog[$k1]['next_storage_num'] = $v1['in_storage_num'] - ($v2['num']);
//                         $packageContentLog[$k1]['user_id'] = $data['user_id'];
//                         $packageContentLog[$k1]['main_id'] = $data['main_id'];
//                         $packageContentLog[$k1]['created_at'] = $data['time'];

                         $materielInfo[] = [
                             'materiel_name' => $v1['materiel_name'],
                             'type_name' => $v1['type_name'],
                             'materiel_no' => $v1['materiel_no'],
                             'in_storage_num' => $v1['in_storage_num'] - ($v2['num']),
                             'alert_num' => $v1['alert_num'],
                             'storage_name' => $v1['storage_name'],
                             'storage_id' => $v1['storage_id'],
                             'num' => $v2['num'],
                         ];

//                         $LogOutPackageData[$k1]['storage_manage_id'] = $v1['id'];
//                         $LogOutPackageData[$k1]['materiel_class_id'] = $v1['materiel_class_id'];
//                         $LogOutPackageData[$k1]['materiel_type_id'] = $v1['type_id'];
//                         $LogOutPackageData[$k1]['storage_id'] = $v1['storage_id'];
//                         $LogOutPackageData[$k1]['mean_cost'] = $v1['materiel_mean_cost'];
//                         $LogOutPackageData[$k1]['out_time'] = $data['time'];
//                         $LogOutPackageData[$k1]['created_at'] = $data['time'];
//                         $LogOutPackageData[$k1]['price'] = $v1['materiel_mean_cost'];
//                         $logOutPackageData[$key]['all_id_type'] = 2;//单据类型;0:无;1:报损;2:销售;3:套餐;
//                         $logOutPackageData[$key]['all_id'] = $packageInfo['id'];//单据id
//                         $LogOutPackageData[$k1]['user_id'] = $data['user_id'];
//                         $LogOutPackageData[$k1]['main_id'] = $data['main_id'];
//                         $LogOutPackageData[$k1]['num'] = $v2['num'];
                     }
                 }
             }

             foreach($packageContentStorageInfo as $v3) {
                 StorageManageModel::where('id', $v3['id'])
                     ->update([
                         'in_storage_num' => DB::raw('in_storage_num - '.$v3['num']),
                         'virtual_storage_num' => DB::raw('virtual_storage_num - '.$v3['num'])
                     ]);
             }

             if(!empty($logOutStorageData)) {
                LogOutStorageModel::insert($logOutStorageData);
             }

             foreach($materielInfo as $vv) {
                 MessageService::sendAlertSms(
                     $vv['materiel_name'],
                     $vv['type_name'],
                     $vv['in_storage_num'],
                     $vv['alert_num'],
                     $data,
                     $vv['storage_id'],
                     $vv['storage_name'],
                     $vv['num']
                 );

                 MessageService::sendOutSms(
                     $vv['materiel_name'],
                     $vv['type_name'],
                     $vv['in_storage_num'],
                     $vv['storage_name'],
                     $vv['num'],
                     $data,
                     $vv['storage_id'],
                     $vv['alert_num'],
                 );

                 MessageService::sendShortSms(
                     $vv['materiel_name'],
                     $vv['type_name'],
                     $vv['in_storage_num'],
                     $data,
                     $vv['storage_name'],
                     $v1['storage_id']
                 );
             }

             CommonService::setAlertFlag($data['main_id']);

//            PackageModel::where('id', $data['id'])->update(['status' => 0]);

//             LogPackageContentModel::insert($packageContentLog);
//             LogOutPackageModel::insert($LogOutPackageData);
             DB::commit();
             return ['code' => 0, 'msg' => 'success', 'data' => ''];
         }
         catch(\Exception $e) {
             DB::rollBack();
             Log::debug('套餐出库：'.var_export($e->getMessage(), true));
             return ['code' => 1, 'msg' => '出库异常', 'data' => ''];
         }
     }
}
